<template>
	<div class="detail-page" :style='{}'>
        <div class="breadcrumb-wrapper" style="width: 100%;">
            <div class="bread_view">
                <el-breadcrumb separator="" class="breadcrumb">
                    <el-breadcrumb-item class="first_breadcrumb" :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item class="second_breadcrumb" v-for="(item,index) in breadList" :key="index">{{item.name}}</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="back_view">
                <el-button class="back_btn" @click="backClick" type="primary">返回</el-button>
            </div>
        </div>
		<div class="detail_view">
			<div class="swiper_view">
				<mySwiper :data="bannerList" :type="3"
					:loop="false"
					:navigation="true"
					:pagination="false"
					:paginationType="1"
					:scrollbar="false"
					:slidesPerView="1"
					:spaceBetween="20"
					:autoHeight="false"
					:centeredSlides="false"
					:freeMode="false"
					:effectType="0"
					:direction="horizontal"
					:autoplay="false"
					:slidesPerColumn="1">
					<template #default="scope">
						<img :style='{}' :src="scope.row?$config.url + scope.row:''">
					</template>
				</mySwiper>
			</div>

			<div class="info_view">
				<div class="title_view">
					<div class="detail_title">
						<span>{{detail.xiangmumingcheng}}</span>
					</div>
				</div>
				<div class="info_item">
					<div class="info_label">项目分类</div>
					<div  class="info_text" >{{detail.xiangmufenlei}}</div>
				</div>
				<div class="info_item">
					<div class="info_label">项目阶段</div>
					<div  class="info_text" >{{detail.xiangmujieduan}}</div>
				</div>
				<div class="info_item">
					<div class="info_label">项目当前阶段</div>
					<div  class="info_text" >{{detail.xiangmudangqianjieduan}}</div>
				</div>
				<div class="info_item">
					<div class="info_label">所属领域</div>
					<div  class="info_text" >{{detail.suoshulingyu}}</div>
				</div>
				<div class="info_item">
					<div class="info_label">所属行业</div>
					<div  class="info_text" >{{detail.suoshuxingye}}</div>
				</div>
				<div class="info_item">
					<div class="info_label">项目目标</div>
					<div  class="info_text" >{{detail.xiangmumubiao}}</div>
				</div>
				<div class="info_item">
					<div class="info_label">所需资源</div>
					<div  class="info_text" >{{detail.suoxuziyuan}}</div>
				</div>
				<div class="info_item">
					<div class="info_label">项目简介</div>
					<div class="info_text scrollable">
						<div class="text-content">{{detail.xiangmujianjie}}</div>
						<div class="view-all-btn" @click="showFullIntro">查看全部</div>
					</div>
				</div>
				<div class="info_item">
					<div class="info_label">进展计划</div>
					<div  class="info_text" >{{detail.jinzhanjihua}}</div>
				</div>
				<div class="info_item">
					<div class="info_label">预期成果</div>
					<div  class="info_text" >{{detail.yuqichengguo}}</div>
				</div>
				<div class="info_item">
					<div class="info_label">提交时间</div>
					<div  class="info_text" >{{detail.tijiaoshijian}}</div>
				</div>
				<div class="info_item">
					<div class="info_label">城市</div>
					<div  class="info_text" >{{detail.chengshi}}</div>
				</div>
				<div class="info_item">
					<div class="info_label">负责人账号</div>
					<div class="info_text">
						{{detail.fuzerenzhanghao}}
						<el-button 
							v-if="user.daoshigonghao" 
							type="primary" 
							size="small" 
							style="margin-left: 10px;" 
							@click="viewPersonalFile(detail.fuzerenzhanghao)">
							查看个人档案
						</el-button>
					</div>
				</div>
				<!-- <div v-if="user?.shifoubiye === '是'">
					<div class="info_item">
						<div class="info_label">园区</div>
						<div class="info_text">{{detail.yuanqu}}</div>
					</div>
					<div class="info_item">
						<div class="info_label">街道</div>
						<div class="info_text">{{detail.jiedao}}</div>
					</div>
				</div>
				<div v-else>
					<div class="info_item">
						<div class="info_label">学校名称</div>
						<div class="info_text">{{detail.xuexiaomingcheng}}</div>
					</div>
					<div class="info_item">
						<div class="info_label">学院名称</div>
						<div class="info_text">{{detail.xueyuanmingcheng}}</div>
					</div>
				</div> -->
				<div class="info_item" v-if="centerType">
					<div class="info_label">是否审核</div>
					<div class="info_text">{{detail.sfsh}}</div>
				</div>
				<div class="info_item" v-if="centerType">
					<div class="info_label">回复内容</div>
					<div class="info_text">{{detail.shhf}}</div>
				</div>
				<div class="btn_view">
					<el-button class="edit_btn" type="primary" v-if="user && user.id && detail.fuzerenzhanghao !== user.xuehao" @click="chatClick">联系TA</el-button>

					<!-- 负责人申请 -->
					<el-button class="cross_btn" v-if="!centerType && !route.query.centerType && user.fuzerenzhanghao" @click="xiangmushenqingonAcross('申请','是','','','')" type="warning">申请</el-button>
					<!-- 导师申请 -->
					<el-button 
					class="cross_btn" 
					v-if="!centerType && !route.query.centerType && user.daoshigonghao" 
					:disabled="isTutorApplied"
					@click="xiangmushenqingonAcross('申请','是','','','')" 
					type="warning">
					{{ isTutorApplied ? '已申请' : '指导申请' }}
					</el-button>
					<!-- 创业者申请 -->
					<el-button 
					class="cross_btn" 
					v-if="!centerType && !route.query.centerType && user.xuehao" 
					:disabled="isApplied"
					@click="xiangmushenqingonAcross('申请','是','','','')" 
					type="warning">
					{{ isApplied ? '已申请' : '立即申请' }}
					</el-button>
				<el-button class="edit_btn" v-if="centerType && (btnAuth('xiangmuxinxi','修改') || user.xuehao === detail.fuzerenzhanghao)" type="primary" @click="editClick">修改</el-button>
					<el-button class="del_btn" v-if="centerType && (btnAuth('xiangmuxinxi','删除') || user.xuehao === detail.fuzerenzhanghao)" type="danger" @click="delClick">删除</el-button>
					<!-- 管理申请按钮 -->
					<el-button 
					v-if="centerType && user.xuehao && user.xuehao === detail.fuzerenzhanghao"
					class="manage_btn"
					type="primary"
					@click="manageApplications">
						管理申请
					</el-button>
					
					<el-button 
					v-if="!isGeneratingReport" 
					class="ai_report_btn" 
					type="primary" 
					@click="aiReportClick">
						AI 报告
					</el-button>
					<div v-else class="ai_report_btn_loading">
						<div class="loader">
							<div class="loader-bar bar-1"></div>
							<div class="loader-bar bar-2"></div>
							<div class="loader-bar bar-3"></div>
							<div class="loader-bar bar-4"></div>
						</div>
					</div>
				</div>
			</div>
		</div>
		
	<!-- AI报告弹窗 -->
	<el-dialog v-model="reportDialogVisible" title="AI报告" width="80%" top="5vh" :fullscreen="isFullscreen" :destroy-on-close="true">
		<template #header>
			<div class="report-dialog-header">
				<span>AI报告</span>
				<el-button link @click="toggleFullscreen">
					<el-icon><FullScreen v-if="!isFullscreen" /><ScaleToOriginal v-else /></el-icon>
				</el-button>
			</div>
		</template>
		<div v-if="reportContent" class="report-content-wrapper">
			<iframe v-if="reportContentType === 'html'" 
				:srcdoc="reportContent" 
				class="report-iframe" 
				frameborder="0"
				sandbox="allow-same-origin allow-scripts allow-popups"
				@load="iframeLoaded"
			></iframe>
			<div v-else v-html="reportContent" class="report-content"></div>
		</div>
		<div v-else-if="reportError" class="report-error">
			<el-alert title="加载报告内容失败" type="error" :closable="false">
				<p>{{ reportError }}</p>
				<el-button link type="primary" @click="retryLoadReport">重试</el-button>
			</el-alert>
		</div>
		<div v-else class="report-loading">
			<el-icon class="is-loading" size="30">
				<Loading />
			</el-icon>
			<p>正在加载报告内容...</p>
		</div>
	</el-dialog>
	
	<!-- 项目简介全文弹窗 -->
	<el-dialog v-model="introDialogVisible" title="项目简介" width="70%" top="10vh">
		<div class="intro-full-content">
			<pre>{{detail.xiangmujianjie}}</pre>
		</div>
	</el-dialog>
		<el-tabs type="border-card" v-model="activeName" class="tabs_view">
			<el-tab-pane label="项目详情" name="first">
				<div v-html="detail.xiangmuxiangqing"></div>
			</el-tab-pane>
		</el-tabs>
		<Approval ref="approvalRef" :tableName="tableName" @shChange="init()"></Approval>
		<el-dialog v-model="chatVisible" @close="clearChat" :title="fname">
			<div class="chat-content" id="chat-content">
				<div v-bind:key="item.id" v-for="item in chatList">
					<div v-if="item.uid==user.id" class="right-content">
						<el-alert v-if="item.format==1" class="text-content" :title="item.content" :closable="false"
								  type="warning"></el-alert>
                        <video v-else-if="item.content.endsWith('.mp4')" controls style="width: 200px;height: 160px">
                            <source  :src="$config.url + item.content">
                        </video>
						<el-image v-else fit="cover" :src="item.content?$config.url + item.content:''" style="width: 100px;height: 100px;" :preview-src-list="[item.content?$config.url + item.content:'']"></el-image>
						<img :src="userAvatar" alt="" style="width: 30px;border-radius: 50%;height: 30px;margin: 0 0 0 10px;" />
					</div>
					<div v-else class="left-content">
						<img :src="fpic?$config.url + fpic:require('@/assets/avatar.png')" alt="" style="width: 30px;border-radius: 50%;height: 30px;margin: 0 10px 0 0;" />
						<el-alert v-if="item.format==1" class="text-content" :title="item.content" :closable="false"
								  type="success"></el-alert>
                        <video v-else-if="item.content.endsWith('.mp4')" controls style="width: 200px;height: 160px">
                            <source  :src="$config.url + item.content">
                        </video>
						<el-image v-else fit="cover" :src="item.content?$config.url + item.content:''" style="width: 100px;height: 100px;" :preview-src-list="[item.content?$config.url + item.content:'']"></el-image>

					</div>
					<div class="clear-float"></div>
				</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-input size="small" @keydown.enter.native="addChat" v-model="chatForm.content" placeholder="请输入内容" style="width: calc(100% - 240px);float: left;border: 1px solid #ccc;margin-right: 10px;">
				</el-input>
				<el-button size="small" :disabled="chatForm.content?false:true" type="primary" @click="addChat">发送</el-button>
				<el-upload style="display: inline-block;margin: 0 6px;" class="upload-demo" :action="uploadUrl" :on-success="uploadSuccess"
						   :show-file-list="false">
					<el-button size="small" type="success">上传文件</el-button>
				</el-upload>
                <el-button size="small" type="primary" @click="sendGoods">详情图发送</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script setup>
	import axios from 'axios'
	import moment from 'moment'
	import {
		ref,
		getCurrentInstance,
		watch,
		onUnmounted,
		onMounted,
		nextTick,
		reactive,
		computed,
		onBeforeUnmount
	} from 'vue';
	import {
		ElMessageBox
	} from 'element-plus'
	import { Loading, FullScreen, ScaleToOriginal } from '@element-plus/icons-vue'
	import {
		useRoute,
		useRouter
	} from 'vue-router';
	import {
		useStore
	} from 'vuex';
	const store = useStore()
	const user = computed(()=>store.getters['user/session'])
	const userAvatar = computed(()=>store.getters['user/avatar'])
	const context = getCurrentInstance()?.appContext.config.globalProperties;
	const route = useRoute()
	const router = useRouter()
	//基础信息
	const tableName = 'xiangmuxinxi'
	const formName = '项目信息'
	// 新增状态变量
	const isGeneratingReport = ref(false);
	const reportCheckInterval = ref(null);
	const reportDialogVisible = ref(false);
	// 添加新的状态变量
	const isFullscreen = ref(false);
	const reportContentType = ref('html');
	const reportError = ref(null);
	const reportContent = ref('');
	//基础信息
	const breadList = ref([{
		name: formName
	}])
	//权限验证
	const btnAuth = (e,a)=>{
		if(centerType.value){
			return context?.$toolUtil.isBackAuth(e,a)
		}else{
			return context?.$toolUtil.isAuth(e,a)
		}
	}
	//查看权限验证
	const btnFrontAuth = (e,a)=>{
		// 负责人可以直接申请自己的项目
		if(user.value.xuehao === detail.value.fuzerenzhanghao) {
			return true
		}
		// 其他情况使用前端权限检查
		return context?.$toolUtil.isFrontAuth(e,a)
	}
	// 返回
	const backClick = () =>{
		history.back()
	}
	// 轮播图
	const bannerList = ref([])
	// 详情
	const title = ref('')
	const detail = ref({})
    const activeName = ref('first')
    // 存储当前导师已申请的项目列表
    const tutorAppliedProjects = ref([])
    // 判断当前项目是否已被导师申请
    const isTutorApplied = computed(() => {
        if (!user.value || !user.value.daoshigonghao || !detail.value.xiangmumingcheng) {
            return false
        }
        return tutorAppliedProjects.value.includes(detail.value.xiangmumingcheng)
    })
    
    // 获取导师已申请的项目列表
    const getTutorAppliedProjects = async () => {
        if (!user.value || !user.value.daoshigonghao) {
            return
        }
        try {
            const res = await context.$http.get('/xiangmushenqing/list', {
                params: {
                    zhidaodaoshi: user.value.daoshigonghao,// 可选，只查询已审核的申请
                }
            })
            if (res.data && res.data.code === 0 && res.data.data && res.data.data.list) {
                // 提取所有已申请项目的名称
                tutorAppliedProjects.value = res.data.data.list.map(item => item.xiangmumingcheng)
                console.log('导师已申请项目列表:', tutorAppliedProjects.value)
            }
        } catch (error) {
            console.error('获取导师已申请项目失败:', error)
        }
    }
    
	const getDetail = async () => {
		try {
			const res = await context?.$http({
				url: `${tableName}/detail/${route.query.id}`,
				method: 'get'
			})
			bannerList.value = res.data.data.xiangmutupian?res.data.data.xiangmutupian.split(','):[]
			title.value = res.data.data.xiangmumingcheng
			if(res.data.data.touxiang){
				fpic.value = res.data.data.touxiang.split(',')[0]
			}else if(res.data.data.headportrait){
				fpic.value = res.data.data.headportrait.split(',')[0]
			}
			detail.value = res.data.data
			
			// 如果是导师用户，获取已申请的项目列表
			if (user.value && user.value.daoshigonghao) {
			    getTutorAppliedProjects()
			}
			
			// 检查AI报告状态
			if (detail.value.xiangmumingcheng) {
				try {
					const checkRes = await context.$http.get('aireport/check', {
						params: {
							xiangmumingcheng: detail.value.xiangmumingcheng
						}
					})
					if (checkRes.data.data) {
						// 报告已生成，显示提示
						context.$toolUtil.message('AI报告已生成，可点击"AI报告"按钮查看', 'success');
					}
				} catch (err) {
					console.error(err);
				}
			}
		} catch (e) {
			console.error('Error fetching detail:', e)
		}
	}
	// 下载文件
	const downClick = (file) => {
		if(!file){
			context?.$toolUtil.message('文件不存在','error')
		}
		let arr = file.replace(new RegExp('file/', "g"), "")
		axios.get((location.href.split(context?.$config.name).length>1 ? location.href.split(context?.$config.name)[0] :'') + context?.$config.name + '/file/download?fileName=' + arr, {
			headers: {
				token: context?.$toolUtil.storageGet('frontToken')
			},
			responseType: "blob"
		}).then(({
			data
		}) => {
			const binaryData = [];
			binaryData.push(data);
			const objectUrl = window.URL.createObjectURL(new Blob(binaryData, {
				type: 'application/pdf;chartset=UTF-8'
			}))
			const a = document.createElement('a')
			a.href = objectUrl
			a.download = arr
			// a.click()
			// 下面这个写法兼容火狐
			a.dispatchEvent(new MouseEvent('click', {
				bubbles: true,
				cancelable: true,
				view: window
			}))
			window.URL.revokeObjectURL(data)
		})
	}
	// 判断是否从个人中心跳转
	const centerType = ref(false)
	const init = () => {
		if(route.query.centerType){
			centerType.value = true
		}
		getDetail()
	}
	//审核
	import Approval from '@/components/approval.vue'
	const approvalRef = ref(null)
	const approvalClick = (btnType='审核') => {
		if(!context?.$toolUtil.storageGet('frontToken')){
			context?.$toolUtil.message('请登录后再操作！','error')
			return false
		}
		if(!btnAuth('xiangmuxinxi',btnType)){
			context?.$toolUtil.message('暂无权限操作！','error')
			return false
		}
		let row = detail.value
		let params = {
			id: row.id,
			sfsh: row.sfsh,
			shhf: row.shhf,
		}
		nextTick(() => {
			approvalRef.value.approvalClick(params)
		})
	}
	//修改
	const editClick = () => {
		router.push(`/index/${tableName}Add?id=${detail.value.id}&&type=edit`)
	}
	//删除
	const delClick = () => {
		ElMessageBox.confirm(`是否删除此${formName}？`, '提示', {
			confirmButtonText: '是',
			cancelButtonText: '否',
			type: 'warning',
		}).then(()=>{
			context?.$http({
				url: `${tableName}/delete`,
				method: 'post',
				data: [detail.value.id]
			}).then(res=>{
				context?.$toolUtil.message('删除成功','success',()=>{
					history.back()
				})
			})

		})
	}
	// 切换全屏方法
	const toggleFullscreen = () => {
		isFullscreen.value = !isFullscreen.value;
	};

	// 重试加载报告
	const retryLoadReport = () => {
		reportError.value = null;
		loadReportContent();
	};

	// 加载报告内容
	const loadReportContent = () => {
		if (!detail.value || !detail.value.xiangmumingcheng) return;
		
		reportContent.value = '';
		
		context.$http.get('aireport/content', {
			params: {
				xiangmumingcheng: detail.value.xiangmumingcheng
			},
			responseType: 'text',
			transformResponse: [data => data] // 防止自动JSON解析
		}).then(contentRes => {
			// 检查内容类型
			const content = contentRes.data;
			
			// 检查是否为HTML内容
			if (typeof content === 'string' && (content.trim().startsWith('<!DOCTYPE html>') || content.trim().startsWith('<html'))) {
				reportContentType.value = 'html';
				reportContent.value = content;
			} else if (typeof content === 'object' && content.data) {
				// 处理嵌套的数据结构
				if (typeof content.data === 'string' && (content.data.trim().startsWith('<!DOCTYPE html>') || content.data.trim().startsWith('<html'))) {
					reportContentType.value = 'html';
					reportContent.value = content.data;
				} else {
					reportContentType.value = 'text';
					reportContent.value = typeof content.data === 'string' ? content.data : JSON.stringify(content.data, null, 2);
				}
			} else {
				reportContentType.value = 'text';
				reportContent.value = typeof content === 'string' ? content : JSON.stringify(content, null, 2);
			}
		}).catch(err => {
			// 尝试从错误对象中提取HTML内容
			if (err && err.data && typeof err.data === 'string' && 
				(err.data.trim().startsWith('<!DOCTYPE html>') || err.data.trim().startsWith('<html'))) {
				reportContentType.value = 'html';
				reportContent.value = err.data;
				return; // 成功提取HTML，不显示错误
			}
			
			// 检查是否有响应数据
			if (err && err.response && err.response.data) {
				const responseData = err.response.data;
				if (typeof responseData === 'string' && 
					(responseData.trim().startsWith('<!DOCTYPE html>') || responseData.trim().startsWith('<html'))) {
					reportContentType.value = 'html';
					reportContent.value = responseData;
					return; // 成功提取HTML，不显示错误
				}
			}
			
			// 如果是HTML内容但被当作错误处理
			if (err && typeof err === 'object') {
				// 遍历错误对象的所有属性，寻找HTML内容
				for (const key in err) {
					if (typeof err[key] === 'string' && 
						(err[key].trim().startsWith('<!DOCTYPE html>') || err[key].trim().startsWith('<html'))) {
						reportContentType.value = 'html';
						reportContent.value = err[key];
						return; // 成功提取HTML，不显示错误
					}
				}
			}
			
			// 只有在确实无法提取有效内容时才显示错误，并提供重试选项
			reportError.value = '报告内容暂时无法加载，请稍后再试';
			
			// 5秒后自动重试
			setTimeout(() => {
				if (reportDialogVisible.value && reportError.value) {
					retryLoadReport();
				}
			}, 5000);
		});
	};

	// 修改AI报告点击事件处理函数
	const aiReportClick = () => {
		// 如果没有项目名称，直接返回
		if (!detail.value || !detail.value.xiangmumingcheng) {
			context.$toolUtil.message('项目信息不完整，无法生成报告', 'warning');
			return;
		}

		// 先显示加载状态
		isGeneratingReport.value = true;

		// 检查报告状态
		context.$http.get('aireport/check', {
			params: {
				xiangmumingcheng: detail.value.xiangmumingcheng
			}
		}).then(res => {
			// 检查响应是否有效
			if (!res || !res.data) {
				// 静默触发生成
				triggerReportGeneration(false);
				return;
			}
			
			// 检查响应状态码
			if (res.data.code === 0) {
				const status = res.data.status || 'unknown';
				
				if (status === 'completed') {
					// 报告已生成完成，显示弹窗并加载内容
					reportDialogVisible.value = true;
					reportContent.value = '';
					reportError.value = null;
					loadReportContent();
					isGeneratingReport.value = false;
				} else if (status === 'generating') {
					// 报告正在生成中，显示提示
					context.$toolUtil.message('AI报告正在生成中，请稍后再试', 'info');
					isGeneratingReport.value = true;
					startReportCheck();
				} else {
					// 报告不存在，静默触发生成
					triggerReportGeneration(false);
				}
			} else {
				// 静默触发生成
				triggerReportGeneration(false);
			}
		}).catch(() => {
			// 出错时静默触发生成
			triggerReportGeneration(false);
		});
	};
	// 触发报告生成的函数
	const triggerReportGeneration = (showDialog = true) => {
		context.$http.get('aireport/generate', {
			params: {
				xiangmumingcheng: detail.value.xiangmumingcheng
			}
		}).then(genRes => {
			if (genRes.data && genRes.data.code === 0) {
				// 显示生成开始的提示
				context.$toolUtil.message('已开始生成AI报告，稍后可点击查看', 'success');
				isGeneratingReport.value = true;
				startReportCheck();
				
				// 如果需要显示弹窗
				if (showDialog) {
					reportDialogVisible.value = true;
					reportContent.value = '';
					reportError.value = '正在生成AI报告，请稍候...';
				}
			} else {
				// 生成失败
				context.$toolUtil.message('AI报告生成请求失败，请稍后再试', 'error');
				isGeneratingReport.value = false;
			}
		}).catch(() => {
			// 生成失败
			context.$toolUtil.message('AI报告生成请求失败，请稍后再试', 'error');
			isGeneratingReport.value = false;
		});
	};

	// 开始定时检查报告状态
	const startReportCheck = () => {
		// 先清除可能存在的定时器
		if (reportCheckInterval.value) {
			clearInterval(reportCheckInterval.value);
		}
		
		// 设置新的定时器
		reportCheckInterval.value = setInterval(() => {
			context.$http.get('aireport/check', {
				params: {
					xiangmumingcheng: detail.value.xiangmumingcheng
				}
			}).then(res => {
				if (res.data && res.data.code === 0) {
					if (res.data.status === 'completed') {
						// 报告已生成完成
						isGeneratingReport.value = false;
						
						// 如果弹窗已打开，直接加载内容
						if (reportDialogVisible.value) {
							loadReportContent();
							reportError.value = null;
						} else {
							// 否则提示用户可以查看
							context.$toolUtil.message('AI报告已生成完成，可以查看', 'success');
						}
						
						// 清除定时器
						clearInterval(reportCheckInterval.value);
						reportCheckInterval.value = null;
					}
				}
			}).catch(() => {
				// 静默处理错误，继续检查
			});
		}, 5000); // 每5秒检查一次
	};

	// 检查报告状态
	const checkReportStatus = () => {
		if (!detail.value || !detail.value.xiangmumingcheng) return;
		
		context.$http.get('aireport/check', {
			params: {
			xiangmumingcheng: detail.value.xiangmumingcheng
			}
		}).then(res => {
			if (res.data.code === 0) {
			if (res.data.status === 'generating') {
				isGeneratingReport.value = true;
				startReportCheck();
			} else {
				isGeneratingReport.value = false;
			}
			}
		}).catch(err => {
			console.error('检查报告状态出错:', err);
		});
	};

	// iframe加载完成事件
	const iframeLoaded = (event) => {
		try {
			// 尝试调整iframe高度以适应内容
			const iframe = event.target;
			if (iframe && iframe.contentWindow) {
				// 添加样式到iframe内容
				const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
				if (iframeDoc) {
					// 创建样式元素
					const style = iframeDoc.createElement('style');
					style.textContent = `
						body { 
							font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
							line-height: 1.6;
						}
						.chart-container {
							width: 100% !important;
							height: 400px !important;
						}
					`;
					iframeDoc.head.appendChild(style);
					
					// 调整图表大小
					if (iframe.contentWindow.echarts) {
						setTimeout(() => {
							const charts = iframe.contentWindow.document.querySelectorAll('[id$="-chart"]');
							charts.forEach(chart => {
								if (iframe.contentWindow.echarts) {
									const chartInstance = iframe.contentWindow.echarts.getInstanceByDom(chart);
									if (chartInstance) {
										chartInstance.resize();
									}
								}
							});
						}, 500);
					}
				}
			}
		} catch (e) {
			console.error('处理iframe加载事件出错:', e);
		}
	};


	const xiangmushenqingonAcross = async (btnType,crossOptAudit,crossOptPay,statusColumnName,tips,statusColumnValue,type=1) => {
		console.log('当前用户信息:', user.value);
		console.log('shifoubiye字段:', user.value?.shifoubiye);
		if(!context?.$toolUtil.storageGet('frontToken')){
			context?.$toolUtil.message('请登录后再操作！','error')
			return false
		}
		if(!btnAuth('xiangmuxinxi',btnType)){
			context?.$toolUtil.message('暂无权限操作！','error')
			return false
		}
		if(crossOptAudit=='是'&&detail.value.sfsh!='是') {
			context?.$toolUtil.message('请审核通过后再操作！','error')
			return false
		}
		context?.$toolUtil.storageSet('crossObj',JSON.stringify(detail.value))
		context?.$toolUtil.storageSet('crossTable',tableName)
		context?.$toolUtil.storageSet('crossStatusColumnName',statusColumnName)
		context?.$toolUtil.storageSet('crossTips',tips)
		context?.$toolUtil.storageSet('crossStatusColumnValue',statusColumnValue)
		if(statusColumnName!=''&&!statusColumnName.startsWith("[")) {
			var obj = detail.value
			for (var o in obj){
				if(o==statusColumnName && obj[o]==statusColumnValue){
					context?.$toolUtil.message(tips,'warning')
					return;
				}
			}
		}
		nextTick(()=>{
			router.push(`/index/xiangmushenqingAdd?type=cross&&id=${detail.value.id}`)
		})
	}
	const fid = ref('')
	const chatVisible = ref(false)
	const chatList = ref([])
	const chatForm = ref({
		content: ''
	})
	const chatTimer = ref(null)
	const uploadUrl = ref(context.$config.url + 'file/upload')
	const fpic = ref('')
	const fname = ref('')

		const chatClick = ()=> {
		if(detail.value.fuzerenzhanghao == user.value.xuehao){
			context.$toolUtil.message('不能给自己发信息','error')
			return false
		}
		context.$http.get('chuangyezhe/query', {
			params: {
				xuehao: detail.value.fuzerenzhanghao
			}
		}).then(res => {
			if (res.data && res.data.code == 0) {
				fid.value = res.data.data.id
				fname.value = res.data.data.xuehao
				if (res.data.data.touxiang) {
					fpic.value = res.data.data.touxiang.split(',')[0]
				} else if (res.data.data.headportrait) {
					fpic.value = res.data.data.headportrait.split(',')[0]
				}
				getChatList()
				chatVisible.value = true
			}
		})
	}
	const sendGoods = ()=>{
		clearTimeout(chatTimer.value)
		context.$http.get('chatfriend/page', {
			params: {
				uid: user.value.id,
				fid: fid.value,
			}
		}).then(obj => {
			if (obj.data && obj.data.code == 0) {
				if (!obj.data.data.list.length) {
					context.$http.post('chatfriend/add', {
						uid: user.value.id,
						fid: fid.value,
						name: fname.value,
						picture: fpic.value,
						type: 2,
					tablename:  'fuzeren' ,
					}).then(res => {
						context.$http.post('chatfriend/add', {
							uid: fid.value,
							fid: user.value.id,
							type: 2,
							tablename: localStorage.getItem('frontSessionTable'),
							name: localStorage.getItem('frontName'),
							picture: localStorage.getItem('headportrait'),
						}).then(res1 => {

						})
					})
				}
				context.$http.post('chatmessage/add', {
					uid: user.value.id,
					fid: fid.value,
					content: bannerList.value[0],
					format: 2
				}).then(res2 => {
					chatForm.value = {
						content: ''
					}
                    scrollFlag.value = true
					getChatList()
				})
			}
		})
	}
    const scrollFlag = ref(true)
	const getChatList = () => {
		context.$http.get('chatmessage/mlist', {
			params: {
				page: 1,
				limit: 1000,
				uid: user.value.id,
				fid: fid.value
			}
		}).then(res => {
			if (res.data && res.data.code == 0) {
				chatList.value = res.data.data.list
				let div = document.getElementsByClassName('chat-content')[0]
				setTimeout(() => {
                    if (div){
                        if(div.scrollTop+div.clientHeight==div.scrollHeight || scrollFlag.value){
                            div.scrollTop = div.scrollHeight
                            scrollFlag.value = false
                        }
                    }
				}, 0)
				chatTimer.value = setTimeout(() => {
					getChatList()
				}, 5000)
			}
		})
	}
	const clearChat = () => {
		clearTimeout(chatTimer.value)
	}
	const uploadSuccess = (res) => {
		if (res.code == 0) {
			clearTimeout(chatTimer.value)
			context.$http.get('chatfriend/page', {
				params: {
					uid: user.value.id,
					fid: fid.value,
				}
			}).then(obj => {
				if (obj.data && obj.data.code == 0) {
					if (!obj.data.data.list.length) {
						context.$http.post('chatfriend/add', {
							uid: user.value.id,
							fid: fid.value,
							name: fname.value,
							picture: fpic.value,
							type: 2,
						tablename:  'fuzeren' ,
						}).then(res => {
							context.$http.post('chatfriend/add', {
								uid: fid.value,
								fid: user.value.id,
								type: 2,
								tablename: localStorage.getItem('frontSessionTable'),
								name: localStorage.getItem('frontName'),
								picture: localStorage.getItem('headportrait'),
							}).then(res1 => {

							})
						})
					}
					context.$http.post('chatmessage/add', {
						uid: user.value.id,
						fid: fid.value,
						content: 'file/' + res.file,
						format: 2
					}).then(res2 => {
						chatForm.value = {
							content: ''
						}
                        scrollFlag.value = true
						getChatList()
					})
				}
			})
		}
	}
	const addChat = () => {
		clearTimeout(chatTimer.value)
		context.$http.get('chatfriend/page', {
			params: {
				uid: user.value.id,
				fid: fid.value,
			}
		}).then(obj => {
			if (obj.data && obj.data.code == 0) {
				if (!obj.data.data.list.length) {
					context.$http.post('chatfriend/add', {
						uid: user.value.id,
						fid: fid.value,
						name: fname.value,
						picture: fpic.value,
						type: 2,
						tablename:  'fuzeren' ,
					}).then(res => {
						context.$http.post('chatfriend/add', {
							uid: fid.value,
							fid: user.value.id,
							type: 2,
							tablename: localStorage.getItem('frontSessionTable'),
							name: localStorage.getItem('frontName'),
							picture: localStorage.getItem('headportrait'),
						}).then(res1 => {

						})
					})
				}
				context.$http.post('chatmessage/add', {
					uid: user.value.id,
					fid: fid.value,
					content: chatForm.value.content,
					format: 1
				}).then(res2 => {
					chatForm.value = {
						content: ''
					}
                    scrollFlag.value = true
					getChatList()
				})
			}
		})
	}

	// 管理申请
	const manageApplications = () => {
		router.push(`/index/xiangmushenqingList?xiangmumingcheng=${detail.value.xiangmumingcheng}`)
	}
	// 在setup()中添加以下代码
	const fuzerenList = ref([])
	const fetchFuzerenList = async () => {
	    try {
	        const res = await context.$http({
	            url: '/xiangmushenqing/page',
	            method: 'get',
	            params: {
	                page: 1,
	                limit: 1000,
	                order: 'desc',
	                sort: 'id'
	            }
	        })
	        if(res?.data?.code === 0) {
	            fuzerenList.value = res.data.data.list.map(item => item.fuzerenzhanghao)
	        }
	    } catch (e) {
	        console.error('获取负责人列表失败:', e)
	    }
	}
	
	// 修改 isApplied 计算属性
	const isApplied = computed(() => {
	    // 检查项目是否属于当前用户
	    return detail.value.fuzerenzhanghao === user.value.xuehao || fuzerenList.value.includes(detail.value.fuzerenzhanghao);
	})
	
	// 在setup()中添加以下代码
	const fetchUserProjects = async () => {
	    try {
	        const userName = user.value.xuehao; // 假设用户名称存储在 xuehao 字段中
	        const res = await context.$http({
	            url: '/xiangmuxinxi/page',
	            method: 'get',
	            params: {
	                fuzerenzhanghao: userName,
	                page: 1,
	                limit: 1000,
	                order: 'desc',
	                sort: 'id'
	            }
	        });
	        if (res?.data?.code === 0) {
	            // 处理获取到的项目信息
	            console.log('用户的项目信息:', res.data.data.list);
	        }
	    } catch (e) {
	        console.error('获取用户项目信息失败:', e);
	    }
	};
	
	// 修改 onMounted 部分
	onMounted(() => {
	    init();
	    fetchFuzerenList(); // 新增负责人列表获取
	    fetchUserProjects(); // 新增用户项目信息获取
	    // 如果有项目名称，检查报告状态
	    if (detail.value && detail.value.xiangmumingcheng) {
	        checkReportStatus();
	    }
	    // 检查报告状态
	    checkReportStatus();
	});
	// 监听项目信息变化
	watch(() => detail.value.xiangmumingcheng, (newVal) => {
		if (newVal) {
			checkReportStatus();
		}
	});
	
	// 在组件卸载前清除定时器
	onBeforeUnmount(() => {
		if (reportCheckInterval.value) {
			clearInterval(reportCheckInterval.value);
			reportCheckInterval.value = null;
		}
		clearChat(); // 确保聊天定时器也被清除
	});
	// 添加到导出对象中
	defineExpose({
		xiangmushenqingonAcross,
		chatVisible,
		chatList,
		chatForm,
		chatClick,
		sendGoods,
		uploadSuccess,
		addChat,
		clearChat,
		uploadUrl,
		fpic,
		fname,
		isApplied,
		fuzerenList,
		fetchFuzerenList,
		aiReportClick,
		isGeneratingReport,
		toggleFullscreen,
		retryLoadReport,
		loadReportContent,
		isFullscreen,
		reportContentType,
		reportError,
		iframeLoaded
	})

	// 项目简介展开折叠
	const isIntroExpanded = ref(false);
	const toggleIntroExpand = () => {
		isIntroExpanded.value = !isIntroExpanded.value;
	};

	// 项目简介弹窗
	const introDialogVisible = ref(false);
	const showFullIntro = () => {
		introDialogVisible.value = true;
	};

	const viewPersonalFile = (fuzerenzhanghao) => {
		// 将负责人账号存储在localStorage中，而不是URL参数
		localStorage.setItem('viewStudentXuehao', fuzerenzhanghao);
		
		// 跳转到个人档案页面，不在URL中添加xuehao参数
		router.push({
			path: '/index/pingdingdengjiList',
			query: {
				centerType: 1
			}
		});
	};

</script>
<style lang="scss" scoped>
	// 返回盒子
	.back_view {
		// 返回按钮
		.back_btn {
			transition: all 0.3s ease;
		}
		// 返回按钮-悬浮
		.back_btn:hover {
			transform: translateX(-5px);
			box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
		}
	}
	// 面包屑盒子
	.bread_view {
		:deep(.breadcrumb) {
			.el-breadcrumb__separator {
				margin: 0 8px;
				color: #909399;
			}
			.first_breadcrumb {
				.el-breadcrumb__inner {
					color: #409EFF;
					font-weight: 500;
				}
			}
			.second_breadcrumb {
				.el-breadcrumb__inner {
					color: #606266;
				}
			}
		}
	}

	.detail_view{
		// 轮播图
		.swiper_view {
			width: 500px;  /* 设置宽度 */
			height: 500px; /* 设置高度 */
			margin-top: 160px; /* 设置上边距 */
			box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
			border-radius: 8px;
			overflow: hidden;
		}
		// 文字区
		.info_view {
			padding: 20px;

			.title_view {
				margin-bottom: 20px;

				.detail_title {
					font-size: 28px;
					font-weight: bold;
					color: #303133;
				}
				.collect_view {
					.iconfont {
					}
					.iconfontActive {
					}
					span {
					}
					.textActive {
					}
				}
				.collect_view:hover {
				}
				.collect_view:active {
				}
			}

			.info_item {
				margin-bottom: 15px;
				display: flex;
				border-bottom: 1px dashed #eee;
				padding-bottom: 10px;
				align-items: flex-start;

				.info_label {
					width: 120px;
					color: #606266;
					font-weight: 500;
					padding-top: 2px;
				}
				.info_text {
					flex: 1;
					color: #303133;
				}
			}
			.btn_view {
				display: flex;
				flex-wrap: wrap;
				gap: 15px;
				margin-top: 25px;
				
				// 跨表-按钮
				.cross_btn {
					transition: all 0.3s ease;
				}
				// 悬浮
				.cross_btn:hover {
					transform: translateY(-3px);
					box-shadow: 0 5px 15px rgba(245, 108, 108, 0.2);
				}
				// 审核-按钮
				.approval_btn {
					transition: all 0.3s ease;
				}
				// 悬浮
				.approval_btn:hover {
					transform: translateY(-3px);
				}
				// 修改-按钮
				.edit_btn {
					transition: all 0.3s ease;
				}
				// 悬浮
				.edit_btn:hover {
					transform: translateY(-3px);
					box-shadow: 0 5px 15px rgba(64, 158, 255, 0.2);
				}
				// 删除-按钮
				.del_btn {
					transition: all 0.3s ease;
				}
				// 悬浮
				.del_btn:hover {
					transform: translateY(-3px);
					box-shadow: 0 5px 15px rgba(245, 108, 108, 0.2);
				}
				// AI报告-按钮
				.ai_report_btn {
					/* From Uiverse.io by Allyhere */ 
					--clr-font-main: hsla(0 0% 20% / 100);
					--btn-bg-1: hsla(194 100% 69% / 1);
					--btn-bg-2: hsla(217 100% 56% / 1);
					--btn-bg-color: hsla(360 100% 100% / 1);
					--radii: 0.5em;
					cursor: pointer;
					padding: 0.9em 1.4em;
					min-width: 120px;
					min-height: 44px;
					font-size: var(--size, 1rem);
					font-weight: 500;
					transition: 0.8s;
					background-size: 280% auto;
					background-image: linear-gradient(
						325deg,
						var(--btn-bg-2) 0%,
						var(--btn-bg-1) 55%,
						var(--btn-bg-2) 90%
					);
					border: none;
					border-radius: var(--radii);
					color: var(--btn-bg-color);
					box-shadow:
						0px 0px 20px rgba(71, 184, 255, 0.5),
						0px 5px 5px -1px rgba(58, 125, 233, 0.25),
						inset 4px 4px 8px rgba(175, 230, 255, 0.5),
						inset -4px -4px 8px rgba(19, 95, 216, 0.35);
				}
				// 悬浮
				.ai_report_btn:hover {
					background-position: right top;
					transform: translateY(-3px);
				}
				
				.ai_report_btn:is(:focus, :focus-visible, :active) {
					outline: none;
					box-shadow:
						0 0 0 3px var(--btn-bg-color),
						0 0 0 6px var(--btn-bg-2);
				}
				
				@media (prefers-reduced-motion: reduce) {
					.ai_report_btn {
						transition: linear;
					}
				}
				
				/* AI报告按钮加载样式 */
				.ai_report_btn_loading {
					display: flex;
					justify-content: center;
					align-items: center;
					min-width: 120px;
					min-height: 44px;
					border-radius: 0.5em;
					background: linear-gradient(325deg, hsla(217, 100%, 56%, 1) 0%, hsla(194, 100%, 69%, 1) 55%, hsla(217, 100%, 56%, 1) 90%);
					box-shadow: 0px 0px 20px rgba(71, 184, 255, 0.5),
						0px 5px 5px -1px rgba(58, 125, 233, 0.25),
						inset 4px 4px 8px rgba(175, 230, 255, 0.5),
						inset -4px -4px 8px rgba(19, 95, 216, 0.35);
				}
			}
		}
	}

	//底部盒子
	.tabs_view {
		margin-top: 30px;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		
		:deep(.el-tabs__header) {
			background: transparent;
			border: none;
		}
		// 头部
		:deep(.el-tabs__nav-scroll) {
			.el-tabs__nav {
				.el-tabs__item {
					padding: 0 20px;
					height: 50px;
					line-height: 50px;
					transition: all 0.3s;
				}
				.el-tabs__item:hover {
					color: #409EFF;
				}
				.is-active {
					font-weight: bold;
				}
			}
		}
		// 内容区
		:deep(.el-tabs__content) {
			padding: 20px;
		}
	}

	/* 项目简介样式 */
	.info_text {
		position: relative;
		max-height: 120px;
		overflow: hidden;
		transition: max-height 0.5s ease;
		padding-bottom: 24px;
		
		.text-content {
			word-break: break-word;
			white-space: pre-wrap;
			line-height: 1.5;
			padding-right: 10px;
		}
		
		.view-all-btn {
			position: absolute;
			bottom: 0;
			right: 0;
			color: #409EFF;
			cursor: pointer;
			padding: 2px 10px;
			background-color: #f0f9ff;
			border: 1px solid #d9ecff;
			border-radius: 4px;
			margin: 0 10px 2px 0;
			font-size: 12px;
			transition: all 0.3s;
			
			&:hover {
				background-color: #ecf5ff;
				color: #66b1ff;
			}
		}
	}
	
	.info_text.scrollable {
		overflow-y: auto;
		display: flex;
		flex-direction: column;
		
		.text-content {
			flex: 1;
		}
		
		&::-webkit-scrollbar {
			width: 6px;
		}
		
		&::-webkit-scrollbar-thumb {
			background-color: #c0c4cc;
			border-radius: 3px;
		}
		
		&::-webkit-scrollbar-track {
			background-color: #f5f7fa;
		}
	}
	
	/* 项目简介弹窗内容 */
	.intro-full-content {
		max-height: 60vh;
		overflow-y: auto;
		padding: 10px;
		background-color: #f5f7fa;
		border-radius: 4px;
		
		pre {
			white-space: pre-wrap;
			word-break: break-word;
			font-family: inherit;
			margin: 0;
			padding: 10px;
		}
		
		&::-webkit-scrollbar {
			width: 8px;
		}
		
		&::-webkit-scrollbar-thumb {
			background-color: #c0c4cc;
			border-radius: 4px;
		}
		
		&::-webkit-scrollbar-track {
			background-color: #e4e7ed;
		}
	}

	/* 报告弹窗样式 */
	.report-dialog-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
	}
	
	.report-content-wrapper {
		width: 100%;
		height: calc(80vh - 120px);
		overflow: auto;
		background-color: #f5f7fa;
		border-radius: 4px;
		padding: 10px;
	}
	
	.report-iframe {
		width: 100%;
		height: 100%;
		border: none;
		overflow: auto;
		background-color: white;
		border-radius: 4px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}
	
	.report-content {
		padding: 15px;
		background-color: #fff;
		border-radius: 4px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		white-space: pre-wrap;
		word-break: break-word;
	}
	
	.report-error {
		padding: 20px;
		text-align: center;
	}
	
	.report-loading {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 200px;
	}
	
	/* 全屏模式下的样式 */
	:deep(.el-dialog.is-fullscreen) {
		.report-content-wrapper {
			height: calc(100vh - 120px);
		}
	}
	
	/* 新的加载动画样式 */
	/* From Uiverse.io by funkyjuice213 */ 
	.loader {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
	}

	.loader-bar {
		height: 25px;
		width: 6px;
		margin: 0 3px;
		border-radius: 20px;
		animation: loader 2s ease-in-out infinite;
	}

	.bar-1 {
		background: linear-gradient(to right, #00e6e6, #00ccff, #0099ff, #0066ff);
		animation-delay: 0s;
		box-shadow: 0px 0px 15px 3px #00e6e6;
	}

	.bar-2 {
		background: linear-gradient(to right, #00ccff, #0099ff, #0066ff, #00e6e6);
		animation-delay: 0.1s;
		box-shadow: 0px 0px 15px 3px #00ccff;
	}

	.bar-3 {
		background: linear-gradient(to right, #0099ff, #0066ff, #00e6e6, #00ccff);
		animation-delay: 0.2s;
		box-shadow: 0px 0px 15px 3px #0099ff;
	}

	.bar-4 {
		background: linear-gradient(to right, #0066ff, #00e6e6, #00ccff, #0099ff);
		animation-delay: 0.3s;
		box-shadow: 0px 0px 15px 3px #0066ff;
	}

	@keyframes loader {
		0% {
			transform: scaleY(1);
		}

		50% {
			transform: scaleY(2);
		}

		100% {
			transform: scaleY(1);
		}
	}
</style>
